package com.waitingresult.thread.dead;

/**
 * All right reserved,Designed By WangShuai
 *
 * @author : WangShuai
 * @version : V1.0
 * @ClassName : DeadLockDemo
 * @Description : 多线程环境下产生死锁的Demo演示
 * @date : 2022/9/16 14:50
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        DeadLockThread deadLockThread1 = new DeadLockThread(true);
        DeadLockThread deadLockThread2 = new DeadLockThread(false);
        new Thread(deadLockThread1).start();
        new Thread(deadLockThread2).start();
    }
}
class DeadLockThread implements Runnable{
    private int index;
    static Object left = new Object();
    static Object right = new Object();
    private boolean flag;

    public DeadLockThread(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if(flag){
            synchronized (left){
                synchronized (right){
                    System.err.println("left 拿到所有锁");
                }
            }
        }else{
            synchronized (right){
                System.err.println("right 拿到锁， 开始锁left");
                synchronized (left){
                    System.err.println("right 拿到所有锁");
                }
            }
        }
    }
}
